package cn.wgx.module.mind.service;

import cn.wgx.common.entity.mind.ProjectUser;
import cn.wgx.common.entity.sys.SysUser;
import cn.wgx.common.security.feign.module.sysuser.SysUserFeign;
import cn.wgx.common.util.StringUtils;
import cn.wgx.module.mind.entity.DTOProjectUser;
import cn.wgx.module.mind.entity.mapper.ProjectUserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class ProjectUserService extends BaseMindService<ProjectUserMapper, ProjectUser> {

    @Autowired
    SysUserFeign sysUserFeign;

    @Transactional(readOnly = true)
    public List<DTOProjectUser> getProUsers(Page page, QueryWrapper<ProjectUser> queryWrapper, String nickName) {
        if (StringUtils.isNotBlank(nickName)) {
//            queryWrapper.inSql("user_id","select user_id from sys_user where nickName like %" + nickName + "%");
            // apply 防止SQL注入
            queryWrapper.apply(" user_id in (select user_id from sys_user where nickName like {0})", "%" + nickName + "%");
        }
        IPage<ProjectUser> e = getBaseMapper().selectPage(page, queryWrapper);
        List<Integer> integerIdList = getIntegerIdList(e.getRecords(), "user_id");
        List<SysUser> usersBySysUserIds = sysUserFeign.findUsersByUserIds(integerIdList);
        List<DTOProjectUser> dtoProjectUsers = new ArrayList<>();
        for (ProjectUser projectUser : e.getRecords()) {
            DTOProjectUser dtoProjectUser = new DTOProjectUser();
            BeanUtils.copyProperties(projectUser, dtoProjectUser);
            for (SysUser sysUser : usersBySysUserIds) {
                if (projectUser.getUser_id().equals(sysUser.getUser_id())) {
                    BeanUtils.copyProperties(sysUser, dtoProjectUser);
                }
            }
            dtoProjectUsers.add(dtoProjectUser);
        }
        return dtoProjectUsers;
    }

    @Transactional(readOnly = true)
    public List<SysUser> getUserListNotInProject(Page<SysUser> page, Integer pro_id, String nickname) {
        if (StringUtils.isBlank(nickname)) {
            nickname = "";
        }
        Page<SysUser> page1 = baseMapper.listUserNotInProject(page, pro_id, "%" + nickname + "%");
        return page1.getRecords();
    }

    public int updateByProId(ProjectUser projectUser) {
        QueryWrapper<ProjectUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pro_id", projectUser.getPro_id());
        queryWrapper.eq("user_id", projectUser.getUser_id());
//        baseMapper.update(projectUser, queryWrapper);
        return baseMapper.update(projectUser, queryWrapper);
    }
}
